package com.xbj.voa.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.xbj.voa.common.config.SystemConstants;
import com.xbj.voa.db.dao.TbCheckinDao;
import com.xbj.voa.db.dao.TbHolidaysDao;
import com.xbj.voa.db.dao.TbWorkdayDao;
import com.xbj.voa.db.pojo.TbCheckin;
import com.xbj.voa.service.CheckinService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;

/**
 * @author: 木火
 * @create: 2024-01-18
 * @description: 签到
 **/
@Service
@Scope("prototype")
public class CheckinServiceImpl implements CheckinService {

    @Resource
    private TbCheckinDao tbCheckinDao;
    @Resource
    private SystemConstants systemConstants;
    @Resource
    private TbHolidaysDao tbHolidaysDao;
    @Resource
    private TbWorkdayDao tbWorkdayDao;
    /**
     * @Author 木火
     * @Date  2024/1/18
     * @Param
     * @Description
     **/
    @Override
    public String validCanCheckin(int userId, String date) {
        //日期类型
        String dateType = "工作日";
        //判断是否为周末
        if(DateUtil.date().isWeekend()){
            dateType = "节假日";
        }

        //查询当天是否为特殊工作日
        boolean isWorkday = tbWorkdayDao.searchTodayIsWorkday(date) != null ? true : false;
        boolean isHoliday = tbHolidaysDao.searchTodayIsHoliday(date) != null ? true : false;

        //查询当天是否为节假日
        if(isHoliday){
           dateType = "节假日";
        }

        if(isWorkday){
            dateType = "工作日";
        }
        if(StringUtils.equals("节假日",dateType)){
            //如果为节假日不需要考勤
            return "节假日不需要考勤";
        }else {
            //工作日可以考勤
            //判断是否在考勤范围内
            String startTime = date + " " + systemConstants.getAttendanceStartTime();
            String endTime = date + " " + systemConstants.getAttendanceEndTime();
            DateTime nowTime = DateUtil.date();
            if(nowTime.before(DateUtil.parse(startTime))){
                return "未到上班考勤开始时间";
            }else if (nowTime.after(DateUtil.parse(endTime))){
                return "上班考勤已截止";
            }else {
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("userId",userId);
                hashMap.put("date",date);
                hashMap.put("startTime",startTime);
                hashMap.put("endTime",endTime);
                boolean b = tbCheckinDao.searchHaveCheckin(hashMap) != null ? true : false;
                return b ? "上班已签到,无需重复签到" :"可以签到";
            }

        }
    }
}
